package cn.tedu.sp11.filter;

import cn.tedu.sp01.util.JsonResult;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //设置过滤器的类型：pre, routing, post, error
    @Override
    public String filterType() {
//        return "pre";
        return FilterConstants.PRE_TYPE;
    }

    //设置过滤器添加的位置顺序号
    @Override
    public int filterOrder() {
        return 6;
    }

    //判断对当前请求，是否要执行过滤代码
    @Override
    public boolean shouldFilter() {
        /*如果调用商品，必须登录才能调用；
         *调用其他服务不必登录
         */
        //得到当前请求的后台服务的服务id
        RequestContext requestContext = RequestContext.getCurrentContext();
        String serviceId = (String) requestContext.get(FilterConstants.SERVICE_ID_KEY);
        //判断服务id是否是“item-service”
        return "item-service".equalsIgnoreCase(serviceId);
    }

    //过滤代码
    @Override
    public Object run() throws ZuulException {
        //http://localhost:3001/item-service/6yu5y4y?token=5j36uy43y4
        //得到request对象
        RequestContext rc = RequestContext.getCurrentContext();
        HttpServletRequest httpServletRequest = rc.getRequest();
        //接受token参数
        String token = httpServletRequest.getParameter("token");
        //如果没有token
        if (StringUtils.isBlank(token)) {
            //1.阻止继续执行
            rc.setSendZuulResponse(false);
            //2.

            String json = JsonResult
                    .err()
                    .code(JsonResult.NOT_LOGIN)
                    .msg("No login!没有登录！")
                    .toString();//转成json字符串
            rc.addZuulRequestHeader("Content-Type", "application/json;charset-UTF-8");
            rc.setResponseBody(json);
        }
        return null;//当前zuul版本中，这个返回值没有启用
    }
}

